package SingleLinkList;

import SingleLinkList.MyNode;

public class MyLinkList<T> {
	private MyNode<T> head;
	private MyNode<T> next;
	private int size;
	
	{
		head=new MyNode<T>();
		next=head;
	}
	
	public MyLinkList(){};
	
	public MyLinkList(T[] array){
		add(array);
	}
	
	public void add(T[] array){
		for (int i=0;i<array.length;++i){
			insertLast(array[i]);
		}
		System.out.println(this);
	}
	
	public void insert(T value,int pos){
		if ((size!=0&&pos>size)||pos<0){
			return;
		}
		MyNode<T> insertNode=new MyNode<T>(value);
		MyNode<T> tempNode,
				  iterator=head;
				
		while (iterator.next!=null&&pos-->0){
			iterator=iterator.next;
		}
		
		tempNode=iterator.next;
		iterator.next=insertNode;
		insertNode.next=tempNode;	
		++size;
		if (next.next!=null){
			next=insertNode;
		}
	}
	
	public void insertFirst(T value){
		insert(value,0);
	}
	
	public void insertLast(T value){
		insert(value,size);
	}

	@SuppressWarnings("unchecked")
	public T remove(int pos)throws Exception{
		if (size==0||pos<0||pos>=size){
			throw new Exception();
		}
		MyNode<T> temp,
				  iterator=head;
		T removeValue=null;
		
		while(pos-->0){
			iterator=iterator.next;
		}
		if (iterator.next!=null){
			--size;
			removeValue=(T)(iterator.next.get());
			temp=iterator.next.next;
			iterator.next=temp;
		}
	
		return removeValue;
	}
	
	public void removeFirst()throws Exception{
		remove(0);
	}
	
	public void removeLast(){
		MyNode<T> iterator = head;
		if (iterator.next==null){
			return;
		}

		while (iterator.next.next!=null) {
			iterator = iterator.next;
		}

		iterator.next = null;

		--size;
		next=iterator;
	}
	
	public int find(T value){
		int index=0;
		MyNode<T> iterator=head.next;
		
		while(iterator!=null&&iterator.get()!=value){
			++index;
			iterator=iterator.next;
		}
		
		if (iterator==null){
			return -1;
		}
			
		return index;
	}
	
	public T get(int index){
		if (index>=size||index<0){
			return null;
		}
		
		MyNode<T> iterator=head.next;
		while(index-->0){
			iterator=iterator.next;
		}
		
		return iterator.get();
	}
	
	public String toString(){
		MyNode<T> iterator=head.next;
		StringBuilder str=new StringBuilder("");
		
		if (iterator==null){
			return null;
		}
		
		while(iterator!=null){
			str.append("["+iterator.get()+"]->");
			iterator=iterator.next;
		}
		
		int length=str.length();
		str.delete(length-2, length);
		return str.toString();
	}
	
	public int getSize(){
		return size;
	}
}
